package apiday07.socket;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 客户端
 */
public class Client {
    private Socket socket;

    public Client() {
        System.out.println("正在尝试建立连接服务端...");
        try {
            socket = new Socket("localhost", 8088);//请求连接的IP地址，对应的端口号
//            socket = new Socket("127.0.0.1",8088);
            System.out.println("连接成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        Scanner sc = new Scanner(System.in);

        try {
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            PrintWriter pw = new PrintWriter(osw, true);

            while (true) {
                String str = sc.nextLine();
                //方法二：
                if("exit".equals(str)){
                    break;
                }
                //方法一：
                /*if ("exit".equalsIgnoreCase(str)) {
                    pw.println(str);
                    break;
                }*/
                pw.println(str);
            }
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }
}
